package com.dai.rpc.loadbanlance.loadbanlancer;

import com.dai.rpc.factory.SingletonFactory;
import com.dai.rpc.loadbanlance.AbstractLoadBalance;
import com.dai.rpc.message.RpcRequest;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.*;

/**
 * 轮询策略
 */
@Slf4j
public class RoundRobinBalance extends AbstractLoadBalance {

    private Integer pos = 0;

    @Override
    protected String doSelect(List<String> serviceUrlList, RpcRequest rpcRequest) {
        Random random = SingletonFactory.getInstance(Random.class);
        return serviceUrlList.get(random.nextInt(serviceUrlList.size()));
    }


    @Override
    protected InetSocketAddress doLoadBalance(Set<String> services) {

        if(services.size() <= 0) return null;
        log.info("使用轮询负载均衡策略...");
        ArrayList<String> list = new ArrayList<>(services);
        synchronized (pos){
            if(pos >= list.size()){
                pos = 0;
            }
            String[] s = list.get(pos).split(",");
            pos++;
            return new InetSocketAddress(s[0],Integer.parseInt(s[1]));

        }

    }

    @Override
    public String name() {
        return "roundRobin";
    }
}
